---
title: "Spring 使用环境变量"
date: 2020-3-10
categories:
- java
- spring
tags:
---

<div id="content">
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#orge7a4c3a">使用 @Value 注解注入环境变量</a></li>
<li><a href="#org7584fb0">注入 application*.yml/properties</a></li>
<li><a href="#orgc105691">SPRING_APPLICATION_JSON 环境变量</a></li>
</ul>
</div>
</div>
<blockquote>
<p>
<a href="https://blog.indrek.io/articles/using-environment-variables-with-spring-boot/">https://blog.indrek.io/articles/using-environment-variables-with-spring-boot/</a>
</p>
</blockquote>
<div class="outline-2" id="outline-container-orge7a4c3a">
<h2 id="orge7a4c3a">使用 @Value 注解注入环境变量</h2>
<div class="outline-text-2" id="text-orge7a4c3a">
<p>
与注入Propery一样的用法
</p>
<div class="org-src-container">
<pre class="src src-java"><span style="font-weight: bold; text-decoration: underline;">@Value</span>(<span style="font-style: italic;">"${DB_URL}"</span>)
<span style="font-weight: bold;">private</span> <span style="font-weight: bold; text-decoration: underline;">String</span> <span style="font-weight: bold; font-style: italic;">dbUrl</span>;
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org7584fb0">
<h2 id="org7584fb0">注入 application*.yml/properties</h2>
<div class="outline-text-2" id="text-org7584fb0">
<p>
假如一个 application.yml 中定义了
</p>
<div class="org-src-container">
<pre class="src src-xml">api.key=${API_KEY:123abc}
</pre>
</div>
<p>
表示从环境变量中取值到property api.key中，如果环境变量中没有则使用默认值 "123abc"
</p>
</div>
</div>
<div class="outline-2" id="outline-container-orgc105691">
<h2 id="orgc105691">SPRING_APPLICATION_JSON 环境变量</h2>
<div class="outline-text-2" id="text-orgc105691">
<p>
Spring Boot 在应用启动的时候会查找 SPRING_APPLICATION_JSON 环境变量，将环境变量的值以JSON解析成property。JSON中，有点号的property使用内嵌对象，像yaml那样
</p>
</div>
</div>
</div>
<div class="status" id="postamble">
<p class="date">Date: 2020-3-10</p>
<p class="author">Author: gdme1320</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
